<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="" method="post">
    <input type="text" name="usr">
    <input type="password" name="pwd">
    <input type="submit" onclick="func(event)">
</form>
<script>
    function func(event){
        var pat=/^\w{5,20}$/;
        usr = document.getElementsByName("usr")[0];
        if(usr.value.search(pat) < 0){
            alert("err");
            event.preventDefault()
        }
    }
</script>
</body>
</html>